define(['util', 'ajax'], function (util, ajax) {
    "use strict";


    var exports = {},
		ViewModel;

    ViewModel = function () {
        var self = this;

        self.name = ko.observable();
        self.companyName = ko.observable();
        self.phone = ko.observable();
        self.email = ko.observable();
        self.description = ko.observable();
        self.imageData = ko.observable();

        self.tempImage = ko.observable();

        self.tempImage.subscribe(function (newValue) {
            var canvas = document.getElementById("imgCanvas");
            util.image.drawImage(canvas, newValue);
            self.imageData(canvas.toDataURL());
        });

        self.tempImage(util.image.checkOrDefault(null));

        self.selectPhoto = function () {
            $("#inputFile").click();
        };

        self.capturePhoto = function () {
            $("#inputFile").click();
        };      

        $.subscribe('filesDropped', function (files) {

            if (files.length == 0) return;
            var fileToLoad = files[0];
            var fileReader = new FileReader();
            fileReader.onload = function (fileLoadedEvent) {
                self.tempImage(fileLoadedEvent.target.result);
            };
            fileReader.readAsDataURL(fileToLoad);
        });

        self.save = function () {

            var form = {
                Name: self.name(),
                CompanyName: self.companyName(),
                Phone: self.phone(),
                Email: self.email(),
                Description: self.description(),
                ImageData: self.imageData()
            };

            ajax.post('Lead', form).done(function (response) {
                if (response.id != '') {
                    window.location = 'show?id=' + response.id;
                }
            });
        };

        self.cancel = function () {
            window.location = "index";
        };
    };

    exports.exec = function (sectionId, model) {
        var viewModel = new ViewModel(model);
        ko.applyBindings(viewModel, document.getElementById(sectionId));
    };
    return exports;
});
